package com.epro.dx.activity;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

import com.epro.dx.R;
import com.epro.dx.task.BaseNeedReLoginTask;
import com.epro.dx.util.ActivityUtil;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.HitBuilders.ScreenViewBuilder;
import com.google.android.gms.analytics.Tracker;
import com.google.android.gms.analytics.ecommerce.ProductAction;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.OrderServiceProvider;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.Logger;
import com.weipu.common.util.StringUtil;

/**
 * 取消订单
 * @author  qsc255
 * @version  [版本号, 2015-2-2]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class CancelOrderActivity extends BaseFragmentActivity implements OnClickListener
{
    private String orderNumber;
    
    private String orderPrice;
    
    private int orderStatus;
    
    private Spinner mSpinner;
    
//    private Spinner refundSpinner;
    
    private TextView cancelorder;
    
    private String reasonStr;
    
    //目前只支持原路返回 所以传值1
    private String refundMethodStr="1";
    
    String UserName;
    
    private Button cancelBtn;
    
    /**
     * 获取订单详情接口
     */
    private OrderServiceProvider orderServiceProvider = ProviderFactory.createOrderServiceProvider();
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Tracker tracker = DXApplication.getContext().getTracker(TrackerName.APP_TRACKER);
        tracker.setScreenName(CancelOrderActivity.class.getSimpleName());
        tracker.send(new HitBuilders.ScreenViewBuilder().build());
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_cancelorder);
        setTitleContent(getString(R.string.title_cancelorder));
        setLeftBtnContent(true, -1);
        orderNumber = getIntent().getStringExtra("orderNumber");
        orderPrice = getIntent().getStringExtra("orderPrice");
        String status= getIntent().getStringExtra("orderStatus");
        if(isNumeric(status)){
        	orderStatus=Integer.parseInt(status);
        }
        initView();
        addTolist();
    }
    
    /**
     * 判断是否为数字类型的字符
     * @param str
     * @return
     */
    public boolean isNumeric(String str){ 
    	if(null==str){
    		return false;
    	}
    	   Pattern pattern = Pattern.compile("[0-9]*"); 
    	   Matcher isNum = pattern.matcher(str);
    	   if( !isNum.matches() ){
    	       return false; 
    	   } 
    	   return true; 
    	}
    /** 初始化控件
     * 
     * @see [类、类#方法、类#成员]
     */
    private void initView()
    {
        mSpinner = (Spinner)findViewById(R.id.Spinner_select);
//        refundSpinner = (Spinner)findViewById(R.id.Spinner_refund);
        cancelorder = (TextView)findViewById(R.id.cancel_ordertv);
        String html =
            "This payment for this order was <b>USD " + orderPrice
                + "</b> We will offer you a refund after the order is cancelled.";
        cancelorder.setText(Html.fromHtml(html));
        cancelBtn=(Button) findViewById(R.id.cancel_confirm_btn);
        cancelBtn.setOnClickListener(this);
    }
    
    /** 
     * <下拉列表装载数据>
     * @see [类、类#方法、类#成员]
     */
    private void addTolist()
    {
        final String[] mItems = getResources().getStringArray(R.array.spinnername);
        ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(this, R.layout.simple_spinner_item, mItems);
        mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mSpinner.setAdapter(mAdapter);
//        String[] refundItems = getResources().getStringArray(R.array.spinnerfund);
//        ArrayAdapter<String> fAdapter = new ArrayAdapter<String>(this, R.layout.simple_spinner_item, refundItems);
//        fAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//        refundSpinner.setAdapter(fAdapter);
//        refundSpinner.setEnabled(false);
        //获取选择项的值
        mSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
        {
            
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
            {
                reasonStr = mItems[position];
                
                //                mSpinner.setPrompt(parent.getItemAtPosition(position).toString());
                // Toast.makeText(CancelOrderActivity.this, "你点击的是:" + reasonStr, 2000).show();
                // parent.setVisibility(View.VISIBLE);
            }
            
            @Override
            public void onNothingSelected(AdapterView<?> parent)
            {
                
            }
            
        });
        
//        refundSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
//        {
//            
//            @Override
//            public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
//            {
////                refundMethodStr = String.valueOf(position);
//            }
//            
//            @Override
//            public void onNothingSelected(AdapterView<?> parent)
//            {
//                
//            }
//            
//        });
    }
    
    public void btnYes()
    {
//        if (orderStatus == ServerConstant.MapKey.ORDER_CSEDITING)
//        {
//            new EndEditOrderAsyncTask().execute();
//        }
//        else
//        {
            new CancelOrderAsyncTask().execute();
//        	new Handler().postDelayed(new Runnable() {
//				
//				@Override
//				public void run() {
//					 CancelOrderActivity.this.setResult(ServerConstant.Parameter.CANCEL_RESULTCODE, new Intent());
//		                AlertToast.alert(CancelOrderActivity.this, R.string.cancel_order_success, 1000);
//		                CancelOrderActivity.this.finish();
//					
//				}
//			}, 3000);
//        }
    }
    
    @Override
    public void onClick(View v)
    {
        if (v.getId() == R.id.cancel_confirm_btn)
        {
           // UserName = GlobalConfig.getInstance().getUserSessionCfg().getUsername();
        	UserName = StringUtil.getConfig(CancelOrderActivity.this,
					ServerConstant.Parameter.PARAMETER_NAME_USER_ACCOUNT);
            new AlertDialog.Builder(CancelOrderActivity.this).setTitle(R.string.confirmation)
                .setCancelable(true)
                .setMessage(R.string.confirm_cancel_order)
                .setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener()
                {
                    
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        btnYes();
                    }
                    
                })
                .setNegativeButton(R.string.btn_no, new DialogInterface.OnClickListener()
                {
                    
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        dialog.dismiss();
                    }
                })
                .create()
                .show();
        }
    }
    
    /**
     * 取消订单
     * @author  qsc255
     * @version  [版本号, 2015-3-10]
     * @see  [相关类/方法]
     * @since  [产品/模块版本]
     */
    protected class CancelOrderAsyncTask extends BaseNeedReLoginTask
    {
        
        @Override
        protected void onPreExecute()
        {
        	cancelBtn.setEnabled(false);
//            showWaitingDialog();
        	showLoadingLayout(null);
        }
        
        @Override
        protected String doInBackground(Void... params)
        {
            boolean flag;
            String str = null;
            try
            {
                flag = orderServiceProvider.cancelOrder(orderNumber, true, reasonStr, refundMethodStr, "13", UserName,
                		ActivityUtil.getCustomerToken(),ActivityUtil.getCustomerID());
                if (flag == true)
                {
                    str = "0";
                }
                else
                {
                    str = "1";
                }
            }
            catch (DxException e)
            {
                return e.getErrCode();
            }
            catch (Exception e)
            {
                Logger.e("CancelOrderActivity", "CancelOrderAsyncTask", e);
            }
            return str;
        }
        
        @Override
        protected void onPostExecute(String result)
        {
        	super.onPostExecute(result);
        	cancelBtn.setEnabled(true);
//        	hideWaitingDialog();
        	hideAllLayout();
            if ("1".equals(result))
            {
                AlertToast.alert(CancelOrderActivity.this, R.string.cancel_order_failed, 1000);
            }
            else if ("0".equals(result))
            {
                CancelOrderActivity.this.setResult(ServerConstant.Parameter.CANCEL_RESULTCODE, new Intent());
                AlertToast.alert(CancelOrderActivity.this, R.string.cancel_order_success, 1000);
                //集成GA衡量交易
                measureCancelOrder();
                CancelOrderActivity.this.finish();
            }
            else if(!isRelogin)
            {
                if (null == ServerConstant.ReturnCode.MESSAGEMAP.get(result))
                {
                    AlertToast.alert(CancelOrderActivity.this, R.string.cancel_order_failed, 1000);
                }
                else
                {
                    
                    AlertToast.alert(CancelOrderActivity.this, ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                }
                
            }
            //dismissProcessDialog();
        }

		@Override
		protected Context setContext() {
			return CancelOrderActivity.this;
		}

		@Override
		protected BaseNeedReLoginTask setTask() {
			return new CancelOrderAsyncTask();
		}
    }
    
    /**
     * 为order解锁
     * @author  qsc255
     * @version  [版本号, 2015-3-10]
     * @see  [相关类/方法]
     * @since  [产品/模块版本]
     */
    protected class EndEditOrderAsyncTask extends AsyncTask<Void, Void, String>
    {
        @Override
        protected void onPreExecute()
        {
            
        }
        
        @Override
        protected String doInBackground(Void... params)
        {
            try
            {
                orderServiceProvider.EditionOrder(orderNumber, "", "");
            }
            catch (DxException e)
            {
                return e.getErrCode();
            }
            catch (Exception e)
            {
                Logger.e("CancelOrderActivity", "EndEditOrderAsyncTask", e);
            }
            return "0";
        }
        
        @Override
        protected void onPostExecute(String result)
        {
            if (!"0".equals(result))
            {
                
                AlertToast.alert(CancelOrderActivity.this, ServerConstant.ReturnCode.MESSAGEMAP.get(result));
            }
            else
            {
                new CancelOrderAsyncTask().execute();
            }
        }
    }
    
    /**
     * 衡量订单取消
     */
    private void measureCancelOrder(){
    	if(null!=orderNumber){
    		System.out.println(">>>>>>>measureCancelOrder--orderNumber::"+orderNumber);
	    	ProductAction productAction  = new ProductAction(ProductAction.ACTION_REFUND)
	    										.setTransactionId(orderNumber);
	    	ScreenViewBuilder builder = new HitBuilders.ScreenViewBuilder().setProductAction(productAction);
	    	
	    	Tracker tracker = ((DXApplication)getApplication()).getTracker(TrackerName.APP_TRACKER);
	    	tracker.setScreenName("Cancel Order");
	    	tracker.send(builder.build());
    	}
    }
}
